import json
import csv

from src.apps.iot.tools.fake_meter import connect_mqtt


class AnalyzeFile:
    def analyze(self, file_name):
        """
        读取txt
        """
        print("-------------{}----------".format(file_name))
        with open(file_name, 'rb') as f:
            result_data = {}
            data_list = []
            for line in f:
                content_line = line.decode()
                A, V, P, E = eval(content_line)
                info = {
                    "current": A,
                    "voltage": V,
                    "power": P,
                    "electricWork": E,
                }
                data_list.append(info)
            result_data["source"] = "txt"
            result_data["data"] = data_list
            client = connect_mqtt()
            client.publish("topic_txt", json.dumps(result_data))

    def analyze_log(self, file_name):
        """
        解析log
        """
        print("-------------{}----------".format(file_name))
        with open(file_name, 'rb') as f:
            for line in f:
                content_line = line.decode()
                A, V, P, E = eval(content_line)
                info = {
                    "current": A,
                    "voltage": V,
                    "power": P,
                    "electricWork": E,
                    "source": "log"
                }
                client = connect_mqtt()
                client.publish("topic_log", json.dumps(info))

    def analyze_csv(self, file_name):
        """
        解析csv
        """
        with open(file_name, 'r', encoding="utf-8") as f:
            reader = csv.reader(f)
            for row in reader:
                info = {
                    "current": row[0],
                    "voltage": row[1],
                    "power": row[2],
                    "electricWork": row[3],
                    "source": "csv"
                }
                client = connect_mqtt()
                client.publish("topic_csv", json.dumps(info))
